<template>
  <view class="mine-container">
    <!-- 1. 顶部导航栏 -->
    <view class="top-nav">
      <text class="nav-title">我的</text>
    </view>

    <!-- 2. 用户核心信息区（头像、姓名、ID） -->
    <view class="user-info">
      <view class="avatar-name-area">
        <image 
          :src="userInfo.avatar || '/static/default-avatar.png'" 
          class="user-avatar"
          mode="widthFix"
        ></image>
        
        <view class="name-status">
          <text v-if="!isLogin" class="unlogin-text">未登录</text>
          <text v-else class="login-username">{{ userInfo.employeeName || '员工' }}</text>
          <text v-if="isLogin" class="user-id">ID: {{ employeeId || '未知' }}</text>
        </view>
      </view>

      <view v-if="isLogin" class="status-toggle" @click="toggleStatus">
        <text :class="{ active: currentStatus === 'online' }">
          {{ currentStatus === 'online' ? '接单中' : '休息中' }}
        </text>
      </view>
    </view>

    <!-- 3. 员工星级展示（仅登录可见） -->
    <view class="star-card" v-if="isLogin">
      <text class="card-title">员工星级</text>
      <view class="star-level-wrap">
        <view class="star-icons">
          <text class="star solid" v-for="i in userInfo.starLevel" :key="i">★</text>
          <text class="star hollow" v-for="i in (5 - userInfo.starLevel)" :key="i + userInfo.starLevel">★</text>
        </view>
        <view class="star-info">
          <text class="star-name">{{ getStarName(userInfo.starLevel) }}</text>
          <text class="star-desc">{{ getStarDesc(userInfo.starLevel) }}</text>
        </view>
      </view>
    </view>

    <!-- 4. 业绩数据 -->
    <view class="performance-card" v-if="isLogin">
      <text class="card-title">业绩数据</text>
      <view class="data-grid">
        <view class="data-item">
          <text class="data-value">{{ userInfo.todayOrderCount || 0 }}</text>
          <text class="data-label">今日单量</text>
        </view>
        <view class="data-item">
          <text class="data-value">{{ userInfo.monthlyOrderCount || 0 }}</text>
          <text class="data-label">当月单量</text>
        </view>
        <view class="data-item">
          <text class="data-value">{{ userInfo.totalOrderCount || 0 }}</text>
          <text class="data-label">累计单量</text>
        </view>
        <view class="data-item">
          <text class="data-value">{{ formatCurrency(userInfo.monthlyIncome) }}</text>
          <text class="data-label">当月收入</text>
        </view>
      </view>
    </view>

    <!-- 5. 用户评价列表（显示员工名称） -->
    <view class="evaluate-card" v-if="isLogin">
      <view class="card-header">
        <text class="card-title">用户评价</text>
        <text class="view-all" @click="toEvaluatePage">查看全部</text>
      </view>

      <!-- 评价加载中状态 -->
      <view class="loading-state" v-if="evaluateLoading">
        <uni-icons type="loading" size="30" color="#5555ff" spin></uni-icons>
        <text class="loading-text">加载评价中...</text>
      </view>
      
      <!-- 接口返回的评价列表（仅3条） -->
      <view class="evaluate-list" v-else-if="realEvaluateList.length > 0">
        <view class="evaluate-item" v-for="(item, index) in realEvaluateList" :key="index">
          <view class="evaluate-header">
            <text class="user-avatar">{{ item.userName.charAt(0) }}</text>
            <view class="evaluate-info">
              <text class="user-name">{{ item.userName }}</text>
              <view class="star-rating small">
                <text class="star" v-for="i in 5" :key="i" :class="{ active: i <= item.star }">★</text>
              </view>
            </view>
            <text class="evaluate-time">{{ item.time }}</text>
          </view>
          <!-- 评价内容超出2行省略 -->
          <text class="evaluate-content">{{ item.content }}</text>
        </view>
      </view>
      
      <!-- 无评价空状态 -->
      <view class="empty-evaluate" v-else>
        <text class="empty-icon">⭐</text>
        <text class="empty-text">暂无用户评价，继续加油哦～</text>
      </view>
    </view>

    <!-- 6. 功能列表 -->
    <view class="function-list">
      <view class="function-item" @click="toAbout">
        <text class="item-text">关于我们</text>
      </view>
      <view class="function-item" @click="toEditInfo">
        <text class="item-text">编辑个人信息</text>
      </view>
      <view class="function-item" @click="toSetting">
        <text class="item-text">设置</text>
      </view>
      <view class="function-item" @click="toEvaluatePage" v-if="isLogin">
        <text class="item-text">评价管理</text>
      </view>
      <view class="function-item logout-item" @click="handleLogout" v-if="isLogin">
        <text class="item-text logout-text">退出登录</text>
      </view>
    </view>

    <!-- 底部导航组件 -->
    <bottom-nav :current-path="currentPagePath"></bottom-nav>
  </view>
</template>

<script>
// 引入必要组件和工具
import bottomNav from '@/pages/components/bottom-nav/bottom-nav.vue';
import request from '@/api/request.js';
import uniIcons from '@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue';

export default {
  components: { 
    bottomNav, 
    uniIcons 
  },
  data() {
    return {
      userInfo: {},               // 用户信息
      employeeId: null,           // 员工ID
      isLogin: false,             // 登录状态
      currentStatus: 'online',    // 接单/休息状态
      currentPagePath: '/pages/Employee/mine/mine',

      // 评价相关
      realEvaluateList: [],       // 评价列表
      evaluateLoading: false,     // 加载状态
      evaluateParams: {           // 分页参数
        pageNo: 1,
        pageSize: 3
      }
    };
  },
  onLoad() {
    this.initUserInfo();
    this.getMineEvaluateList();
  },
  onShow() {
    this.initUserInfo();
    this.getMineEvaluateList();
  },
  methods: {
    /**
     * 初始化用户信息
     */
    initUserInfo() {
      const token = uni.getStorageSync('token');
      const cacheUserInfo = uni.getStorageSync('userInfo') || {}; 

      this.isLogin = !!token;
      this.userInfo = { ...cacheUserInfo };

      if (this.isLogin) {
        this.fetchComprehensiveStats(token);
      }
    },

    /**
     * 获取员工业绩统计数据
     */
    fetchComprehensiveStats(token) {
      uni.request({
        url: 'http://localhost:6013/order-client/api/employeeStatistics/comprehensiveStats',
        method: 'POST',
        header: { 
          'content-type': 'application/json',
          'Token': token
        },
        success: (res) => {
          if (res.data.code === 0 && res.data.data) {
            const statsData = res.data.data;
            this.userInfo = {
              ...this.userInfo,
              employeeId: statsData.employeeId,
              employeeName: statsData.employeeName || `员工${statsData.employeeId}`,
              starLevel: statsData.starLevel || 1,
              todayOrderCount: statsData.todayOrderCount || 0,
              monthlyOrderCount: statsData.monthlyOrderCount || 0,
              totalOrderCount: statsData.totalOrderCount || 0,
              monthlyIncome: statsData.monthlyIncome || 0,
            };
            this.employeeId = statsData.employeeId;
            uni.setStorageSync('userInfo', this.userInfo);
          } else {
            uni.showToast({
              title: res.data.msg || '获取统计数据失败',
              icon: 'none'
            });
          }
        },
        fail: () => {
          uni.showToast({ title: '网络错误，无法获取统计数据', icon: 'none' });
        }
      });
    },

    /**
     * 获取评价列表（核心修改：显示员工名称）
     */
    async getMineEvaluateList() {
      const token = uni.getStorageSync('token');
      if (!token) return;

      this.evaluateLoading = true;
      try {
        const response = await request.postJson(
          '/api/customerFeedback/queryPageList',
          this.evaluateParams,
          true,
          { Token: token }
        );

        const pageData = response.data?.data || response;
        const evaluates = (pageData.records || []).map(dto => {
          // 关键修改：从workOrderInfo中获取员工名称，与评价页保持一致
          let userName = (dto.workOrderInfo && dto.workOrderInfo.employeeName) || '匿名员工';
          if (!userName || userName.trim() === '匿名') {
            userName = '匿名员工';
          }

          return {
            userName: userName,          // 显示员工名称（如"特色tqq"）
            star: dto.rating || 0,
            time: this.formatDate(dto.createTime),
            content: dto.comment || '无评价内容',
            orderId: dto.orderId || ''
          };
        });

        this.realEvaluateList = evaluates;

      } catch (error) {
        let errMsg = '获取评价失败，请重试';
        if (error.code === 100003) {
          errMsg = '登录已过期，请重新登录';
          uni.removeStorageSync('token');
          setTimeout(() => uni.redirectTo({ url: '/pages/login/login' }), 1500);
        }
        uni.showToast({ title: errMsg, icon: 'none' });
      } finally {
        this.evaluateLoading = false;
      }
    },

    /**
     * 时间格式化
     */
    formatDate(date) {
      if (!date) return '';
      if (typeof date === 'string' && date.includes('T') && date.includes('+')) {
        date = date.split('+')[0].replace('T', ' ');
      }
      const dateObj = new Date(date);
      const year = dateObj.getFullYear();
      const month = String(dateObj.getMonth() + 1).padStart(2, '0');
      const day = String(dateObj.getDate()).padStart(2, '0');
      const hour = String(dateObj.getHours()).padStart(2, '0');
      const minute = String(dateObj.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hour}:${minute}`;
    },

    /**
     * 金额格式化
     */
    formatCurrency(amount) {
      if (!amount) return '0.00';
      const num = typeof amount === 'number' ? amount : parseFloat(amount);
      return isNaN(num) ? '0.00' : num.toFixed(2);
    },

    /**
     * 接单/休息状态切换
     */
    toggleStatus() {
      this.currentStatus = this.currentStatus === 'online' ? 'offline' : 'online';
      uni.showToast({
        title: this.currentStatus === 'online' ? '已切换为接单状态' : '已切换为休息状态',
        icon: 'none',
        duration: 1500
      });
    },

    /**
     * 获取星级名称
     */
    getStarName(level) {
      const starNames = ['一星员工', '二星员工', '三星员工', '四星员工', '五星员工'];
      return starNames[level - 1] || '一星员工';
    },

    /**
     * 获取星级描述
     */
    getStarDesc(level) {
      const starDescs = [
        '新手员工，正在熟悉工单处理流程',
        '熟练员工，能高效完成基础工单任务',
        '优秀员工，工单处理质量与速度双优',
        '资深员工，可处理复杂工单并指导新人',
        '王牌员工，行业专家级工单处理能力'
      ];
      return starDescs[level - 1] || '新手员工，正在熟悉工单处理流程';
    },

    /**
     * 导航方法
     */
    toAbout() { uni.navigateTo({ url: '/pages/mine/about' }); },
    toSetting() { uni.navigateTo({ url: '/pages/Employee/mine/setting' }); },
    toEvaluatePage() { uni.navigateTo({ url: '/pages/Employee/mine/evaluate' }); },
    toEditInfo() { uni.navigateTo({ url: '/pages/Employee/mine/editInfo' }); },

    /**
     * 退出登录
     */
    handleLogout() {
      uni.showModal({
        title: '确认退出',
        content: '退出后需重新登录，是否继续？',
        success: (res) => {
          if (res.confirm) {
            uni.removeStorageSync('token');
            uni.removeStorageSync('userInfo');
            this.isLogin = false;
            this.userInfo = {};
            this.employeeId = null;
            this.realEvaluateList = [];
            uni.reLaunch({ url: '/pages/login/login' });
          }
        }
      });
    }
  }
};
</script>

<style scoped>
/* 页面容器基础样式 */
.mine-container {
  display: flex;
  flex-direction: column;
  min-height: calc(100vh - 120rpx);
  background-color: #f5f7fa;
  padding-bottom: 120rpx;
  box-sizing: border-box;
}

/* 顶部导航栏 */
.top-nav {
  height: 100rpx;
  background-color: #5555ff;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}
.nav-title {
  font-size: 36rpx;
  color: #fff;
  font-weight: bold;
}

/* 用户信息区 */
.user-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx 24rpx;
  background-color: #fff;
  margin-bottom: 16rpx;
}
.avatar-name-area {
  display: flex;
  align-items: center;
}
.user-avatar {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  border: 2rpx solid #f0f0f0;
  margin-right: 24rpx;
}
.name-status {
  display: flex;
  flex-direction: column;
}
.unlogin-text {
  font-size: 32rpx;
  color: #666;
}
.login-username {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
}
.user-id {
  font-size: 22rpx;
  color: #999;
  margin-top: 8rpx;
}
.status-toggle {
  padding: 10rpx 24rpx;
  border-radius: 24rpx;
  background-color: #f0f0f0;
  font-size: 26rpx;
  color: #666;
  cursor: pointer;
  transition: all 0.2s;
}
.status-toggle text.active {
  color: #5555ff;
  font-weight: 500;
}
.status-toggle:active {
  background-color: #e5e5e5;
}

/* 员工星级卡片 */
.star-card {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin: 0 24rpx 24rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}
.star-level-wrap {
  display: flex;
  align-items: center;
  gap: 20rpx;
}
.star-icons {
  display: flex;
  align-items: center;
}
.star.solid {
  font-size: 40rpx;
  color: #ffd700;
  margin-right: 10rpx;
}
.star.hollow {
  font-size: 40rpx;
  color: #eee;
  margin-right: 10rpx;
}
.star-info {
  display: flex;
  flex-direction: column;
}
.star-name {
  font-size: 30rpx;
  color: #333;
  font-weight: 600;
  margin-bottom: 6rpx;
}
.star-desc {
  font-size: 22rpx;
  color: #666;
}

/* 业绩数据卡片 */
.performance-card {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin: 0 24rpx 24rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}
.card-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 24rpx;
}
.data-grid {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
.data-item {
  width: 48%;
  text-align: center;
  margin-bottom: 20rpx;
  padding: 16rpx 0;
  background-color: #f9f9f9;
  border-radius: 12rpx;
}
.data-value {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
  display: block;
}
.data-label {
  font-size: 24rpx;
  color: #666;
}

/* 评价卡片 */
.evaluate-card {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin: 0 24rpx 24rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
}
.view-all {
  font-size: 26rpx;
  color: #5555ff;
  cursor: pointer;
}

/* 评价加载中样式 */
.loading-state {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 60rpx 0;
  color: #5555ff;
  font-size: 26rpx;
}
.loading-text {
  margin-top: 16rpx;
}

/* 评价列表 */
.evaluate-list {
  margin-bottom: 16rpx;
}
.evaluate-item {
  padding: 20rpx 0;
  border-bottom: 1rpx dashed #f0f0f0;
}
.evaluate-item:last-child {
  border-bottom: none;
}
.evaluate-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12rpx;
}
.evaluate-info {
  display: flex;
  flex-direction: column;
  flex: 1;
}
.user-avatar {
  width: 50rpx;
  height: 50rpx;
  border-radius: 50%;
  background-color: #5555ff;
  color: #fff;
  font-size: 24rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16rpx;
}
.user-name {
  font-size: 26rpx;
  margin-bottom: 4rpx;
}
.star-rating.small .star {
  font-size: 20rpx;
}
.star.active {
  color: #ffd700;
}
.evaluate-time {
  font-size: 22rpx;
  color: #999;
}
.evaluate-content {
  font-size: 26rpx;
  color: #666;
  line-height: 1.5;
  word-break: break-all;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

/* 无评价空状态 */
.empty-evaluate {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 60rpx 0;
  color: #999;
}
.empty-icon {
  font-size: 60rpx;
  margin-bottom: 16rpx;
}
.empty-text {
  font-size: 26rpx;
}

/* 功能列表 */
.function-list {
  background-color: #fff;
  margin: 0 24rpx;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}
.function-item {
  display: flex;
  align-items: center;
  padding: 32rpx;
  border-bottom: 1rpx solid #f5f5f5;
  cursor: pointer;
  transition: background-color 0.2s;
}
.function-item:last-child {
  border-bottom: none;
}
.function-item:active {
  background-color: #f9f9f9;
}
.item-text {
  font-size: 30rpx;
  color: #333;
  margin-left: 20rpx;
}
.logout-item {
  margin-top: 24rpx;
  background-color: #fff5f5;
  border-radius: 16rpx;
  margin: 24rpx;
}
.logout-text {
  color: #ff4d4f;
}
</style>
